package cn.zl.rtsp.response.core;

import cn.hutool.core.util.StrUtil;
import cn.zl.rtsp.response.RTSPResponse;
import cn.zl.rtsp.udp.UDPPort;
import cn.zl.rtsp.udp.UDPPortManage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;

/**
 * 处理setup方法，播放和推流协商rtp传输方式用
 * */
public class SetupRTSPResponse extends RTSPResponse {

    public SetupRTSPResponse(ChannelHandlerContext context, DefaultHttpRequest request) {
        super(context, request);
    }

    @Override
    public void decodeRTSPParam() {
        super.decodeRTSPParam();
        HttpHeaders headers = request.headers();
        this.transport= headers.get("Transport");
        if (StrUtil.isNotBlank(transport)) {
            if (transport.contains("RTP/AVP/TCP")) {
                session.rtpTcp(true);
            } else {
                session.rtpTcp(false);
                getUDPClientPort();
                // 获取 可用的 UDP 端口
                UDPPort port = UDPPortManage.getInstance().getUDPPort();
                session.rtpServerPort(port.getRtp());
                session.rtcpServerPort(port.getRtcp());
                session.initUDPSocket();
            }
        }
    }

    @Override
    protected void write(StringBuilder builder) {
        builder.append("CSeq: ").append(cseq).append(R_N);
        if (session.isRtpTcp()) {
            builder.append("Transport: ").append(transport).append(R_N);
        } else {
            builder.append("Transport: ").append(transport)
                    .append(";server_port=").append(StrUtil.format("{}={}",session.getRtpServerPort(), session.getRtcpServerPort())).append(R_N);
        }
        builder.append("Session: ").append(session.getId()).append(R_N);
    }

}
